<?php

namespace app\cps\middleware;

use think\facade\Request;
use think\facade\Input;
use app\common\Error;
use think\facade\Cache;
use think\facade\Db;

/**
 * 检测是否登录cps
 */
class CheckCpsLogin
{
    public function handle($request, \Closure $next)
    {
        $header = Request::header();
        $redis = Cache::store('redis')->handler();
        $redis->select(3);

        if (!empty($header['token'])) {
            $data = $redis->get($header['token']);
            $result = json_decode($data, true);
        }

        // 访问服务器控制
        if (!empty($result['cps_user_id'])) {
            $host = Request::host();
            $data = Db::name('responsibility_person')->where(['id' => $result['cps_user_id']])->field('is_distributor, pid')->find();
            if (!empty($data['is_distributor']) || !empty($data['pid']) || $host == 'test.sybyn.top') {
                // 
            } else {
                if ($host == config('app.app_host')) {
                    return json(['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::PLEASE_USE_HT_LIUYIYINGSHI_CN_DOMAIN_NAME_ACCESS]);
                }
            }
        }

        // 是否需要token
        $url = Request::controller() . '/' . Request::action();

        $requestUrl = strtolower($url);

        $notAuthRequestUrl = [
            'link/tiktokcallback',
            'link/test',
            'link/testing',
            'link/callback',
            'link/monitoringlink',
            'link/refreshtoken',
            'link/kwaimonitoringlink',
            'link/kwaicallback',
            'link/baidumonitoringlink',
            'link/geturlscheme',
            'account/batchupdate',
            'link/tiktokmonitoringlink',
            'link/baiducallback',
            'link/weibocallback',
            'link/tencentmonitoringlink',
            'link/weibomonitoringlink',
            'link/tiktokcallback1',
            'link/tiktoksubjectauth',
            'link/tiktokcallback2',
            'order/distributionorderlist',
            'user/distributionuserlist',
            'pitcher/selectlist',
            'tencent/gettencentadaccesstoken',
            'tencent/gettencentadcode',
            'link/distributionlinklist',
            'link/bilibiliservice',
            'link/weiboRegister',
            'link/weiboPay',
        ];

        if (!in_array($requestUrl, $notAuthRequestUrl)) {

            // 判断是否传token
            if (!empty($header['token'])) {
                $token = $header['token'];
            } else if (!empty(Request::param()['token'])) {
                $token = Request::param()['token'];
            } else {
                $token = '';
            }

            if (empty($token)) {
                return redirect(url('cps/login/index'));
                // return json(['code' => Error::NOT_LOGGED_CODE, 'message' => Error::PLEASE_LOGIN_FIRST]);
            }

            $data = $redis->get($token);
            $result = json_decode($data, true);

            if (empty($result) || empty($result['cps_user_id'])) {
                return redirect(url('cps/login/index'));
                // return json(['code' => Error::NOT_LOGGED_CODE, 'message' => Error::PLEASE_LOGIN_FIRST]);
            }

            $notOperateLogUrl = [
                'Index/orderStatistics',
                'Index/index',
                'Index/statistics',
                'Index/rechargeStatistics',
                'Back/alreadyReturn',
                'Back/notEchoList',
                'Back/notReturn',
                'Link/list',
                'Link/getLaunchMedia',
                'Video/select',
                'Order/detailed',
                'Order/detailedList',
                'User/index',
                'User/list',
                'Back/alreadyEchoList',
                'Back/unpaidUserManualReturn',
                'Launch/overview',
                'Launch/overviewStatistics',
                'Launch/launchDataList',
                'Launch/getLaunchMedia',
                'Launch/realTime',
                'Launch/investing',
                'Launch/kwaiRealTime',
                'Launch/kwaiInvesting',
                'Launch/baiduRealTime',
                'Launch/baiduInvesting',
                'OfficialAccount/info',
                'OfficialAccount/detail',
                'OfficialAccount/menu',
                'OfficialAccount/appletSelectUrl',
                'Keyword/index',
                'Keyword/list',
                'OfficialAccount/follow',
                'OfficialAccount/linkSelect',
                'OfficialAccount/sign',
                'Account/index',
                'Account/list',
                'Account/companySelectList',
                'Video/index',
                'Video/list',
                'Video/configIndex',
                'Video/configList',
                'Recharge/default',
                'Recharge/defaultCharge',
                'Recharge/index',
                'Index/videoIndex',
                'Index/videoStatistics',
                'Index/videoStatisticsList',
                'User/statisticsIndex',
                'User/statistics',
                'User/lastStatistics',
                'User/newUserRechargeAnalysis',
                'Recharge/list',
                'Link/accountSelectList',
                'Recharge/select',
                'Link/detail',
                'User/info',
                'User/getData',
                'Link/index',
                'Back/manualReturnRecord',
                'Launch/byVideo',
                'Launch/byShortPlay',
                'Video/set',
                'Launch/info',
                'Launch/detail',
                'User/detail',
                'Video/info',
                'Video/detail',
                'Link/info',
                'Video/detailInfo',
                'Video/detailCharge',
                'Order/list',
                'Order/index',
                'Tencent/getTencentAdAccessToken',
                'Tencent/getTencentAdCode',
                'Tencent/tencentInvesting',
            ];
            if (!in_array($url, $notOperateLogUrl)) {
                // 添加操作日志
                Db::name('operate_log')->insert([
                    'official_account_id' => empty($result['cps_used_official_account_id']) ? 0 : $result['cps_used_official_account_id'],
                    'responsibility_person_id' => empty($result['cps_user_id']) ? 0 : $result['cps_user_id'],
                    'url' => 'cps/'.$url,
                    'param' => json_encode(Request::param()),
                    'created_at' => time()
                ]);
            }

        }

        // 限制接口请求频率
        $notLimitRequestFrequency = [
            'link/callback',
            'link/monitoringlink',
            'link/kwaimonitoringlink',
            'link/baidumonitoringlink',
            'link/tiktokmonitoringlink',
            'link/geturlscheme',
            'recharge/getpisplayobject',
            'link/weibomonitoringlink',
            'link/tencentmonitoringlink',
            'link/test',
            'tencent/gettencentadaccesstoken',
            'tencent/gettencentadcode',
            'link/bilibiliservice'
        ];
        if (!in_array($requestUrl, $notLimitRequestFrequency)) {
            
            if (!empty($result['cps_user_id'])) {
                $uuid = $result['cps_user_id'];
            } else if (!empty(Request::param()['token'])) {
                $uuid = Request::param()['token'];
            } else {
                $uuid = '';
            }
            // $uuid = !empty($result['cps_user_id']) ? $result['cps_user_id'] : Request::param()['token'];
            $key = config('redis_key.cps_limit_request_frequency').$uuid.'-'.$requestUrl;

            $redis->select(9);
            $data = $redis->hGetAll($key);

            $delKey = [];
            $total = 0;
            $maxFrequency = 40;
            $limitTime = 10;
            $nowTime = time();

            if ($data) {
                foreach ($data as $time => $count) {
                    if ($time < $nowTime - $limitTime) {
                        $delKey[] = $time;
                    } else {
                        $total += $count;
                    }
                }
            }

            if ($delKey) {
                $redis->hDel($key, ...$delKey);
            }
            if ($total > $maxFrequency) {
                echo json_encode(['code' => '500', 'message' => '操作过于频繁', 'data' => []]);
                die;
            }

            $redis->hIncrBy($key, $nowTime, 1);
            $redis->expire($key, 120);
        }

        return $next($request);
    }
}